//////////////////////////////////////////////////////////////////////
// (c) 2003-2010 sonofdelphi
// MIT License
//////////////////////////////////////////////////////////////////////

#include "Helper.h"

CHelper::CHelper(int nOptions)
{
	int i;
	m_nOptions=nOptions;
	
	//Initialize help area
	m_asHelp=new char* [m_nOptions];
	for(i=0;i<m_nOptions;i++)
		m_asHelp[i]=NULL;

	//Initialize intro message
	m_sProgramName=NULL;
	m_sAuthor = NULL;
	m_sOwner = NULL;
	m_sYear = NULL;
	m_sSummary=NULL;
	m_sUsageLine=NULL;
	m_sTailMessage=NULL;
}

CHelper::~CHelper()
{
	for(int i=0;i<m_nOptions;i++)
		if(m_asHelp[i])	delete[] m_asHelp[i];
	
	if(m_asHelp) 		delete[] m_asHelp;
	if(m_sProgramName) 	delete[] m_sProgramName;
	if(m_sAuthor) 		delete[] m_sAuthor;
	if(m_sOwner) 		delete[] m_sOwner;
	if(m_sYear)			delete[] m_sYear;
	if(m_sSummary)		delete[] m_sSummary;
	if(m_sUsageLine)	delete[] m_sUsageLine;
	if(m_sTailMessage)	delete[] m_sTailMessage;
}

void CHelper::fillProgramName(char *strMessage)
{
	deleteAndCopy(&m_sProgramName,strMessage);
}

void CHelper::fillAuthor(char *strMessage)
{
	deleteAndCopy(&m_sAuthor,strMessage);
}

void CHelper::fillYear(char *strMessage)
{
	deleteAndCopy(&m_sYear,strMessage);
}

void CHelper::fillOwner(char *strMessage)
{
	deleteAndCopy(&m_sOwner,strMessage);
}

void CHelper::fillSummary(char *strMessage)
{
	deleteAndCopy(&m_sSummary,strMessage);
}

void CHelper::fillUsageLine(char *strMessage)
{
	deleteAndCopy(&m_sUsageLine,strMessage);
}

void CHelper::fillTailMessage(char *strMessage)
{
	deleteAndCopy(&m_sTailMessage,strMessage);
}

void CHelper::fillHelpForOption(int nPos, char cOption, char* strValue)
{
	if(nPos>=m_nOptions)
		return;	//throw exception

	if(m_asHelp[nPos]) delete[] m_asHelp[nPos];
	m_asHelp[nPos]=new char[1+strlen(strValue)+1];
	m_asHelp[nPos][0]=cOption;
	strcpy(m_asHelp[nPos]+1,strValue);
}

char** CHelper::getBuffer()
{
	return m_asHelp;
}

void CHelper::deleteAndCopy(char **dest, char *source)
{
	if(*dest) delete[] *dest;
	*dest=new char[strlen(source)+1];
	strcpy(*dest,source);
}

void CHelper::displayHelp()
{
	using namespace std;

	if(m_sProgramName)	cout<<m_sProgramName;
	if(m_sSummary)		cout<<" - "<<m_sSummary<<endl; else cout<<endl;
	if(m_sYear)			cout<<"(C)"<< m_sYear << " ";
	if(m_sOwner)			cout<<m_sOwner<<endl; else cout<<endl; 
	if(m_sAuthor) 		cout<<"Developed by " << m_sAuthor<<endl;
	if(m_sUsageLine)		
	{
		cout<<std::endl<<"USAGE: ";
		if(m_sProgramName) cout<<m_sProgramName<<" ";
		cout<<m_sUsageLine<<endl;
	}
	
	std::cout<<std::endl<<"OPTIONS"<<std::endl;
	for(int i=0;i<m_nOptions;i++){
		if(m_asHelp[i])
			std::cout<<m_asHelp[i][0]<<"\t- "<<m_asHelp[i]+1<<std::endl;
	}

	if(m_sTailMessage)	
		std::cout<<std::endl<<m_sTailMessage<<std::endl;
}
